#include "MainWindow.h"
#include <iostream>
#include <QList>
#include <QListIterator>
#include <QTreeWidgetItem>
#include <QPrinter>
#include <QPrintDialog>
#include <QPainter>
#include <QHBoxLayout>
#include <QFileDialog>
#include <QPalette>
#include "QuorumType.h"
#include "YouthManager.h"
#include "DeaconsRequirements.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent), m_youth(YouthManager::getInstanceOf()),
            m_current(NULL)
{
    setupUi(this);
    
    for(QuorumType::Type quorum = QuorumType::Deacon;
        quorum <= QuorumType::Retired; ++quorum)
    {
    	YouthTreeWidget->addTopLevelItem(new QTreeWidgetItem(QStringList(QuorumType::NameOf(quorum))));
    }
    YouthTreeWidget->expandAll();
    
    connect(YouthTreeWidget, SIGNAL(itemSelectionChanged()), this,
            SLOT(youthSelectionChanged()));

    connect(YouthManager::getInstanceOf(), SIGNAL(youthListUpdated()), this,
            SLOT(redisplayYouth()));

    connect(actionPrint, SIGNAL(triggered()), this, SLOT(print()));
    connect(actionQuit, SIGNAL(triggered()), this, SLOT(close()));
    connect(actionOpen, SIGNAL(triggered()), this, SLOT(open()));
    connect(actionSave_As, SIGNAL(triggered()), this, SLOT(saveas()));
    connect(actionSave, SIGNAL(triggered()), this, SLOT(save()));
    
    connect(actionDeacon, SIGNAL(triggered()), 
    		YouthManager::getInstanceOf(), SLOT(newDeacon()));
    connect(actionTeacher, SIGNAL(triggered()), 
    		YouthManager::getInstanceOf(), SLOT(newTeacher()));
    connect(actionPriest, SIGNAL(triggered()), 
    		YouthManager::getInstanceOf(), SLOT(newPriest()));

    empty = new QWidget();
    deaconwidget = new DeaconsWidget();
    m_layout = new QStackedLayout(RequirementsGroup);
    
    m_layout->addWidget(empty);
    m_layout->addWidget(deaconwidget);

    //    teacherwidget = new TeachersRequirements(RequirementsGroup);
    //    priestwidget = new PriestsRequirements(RequirementsGroup);
    //    retiredwidget = new RetiredRequirements(RequirementsGroup);

}

MainWindow::~MainWindow()
{
}

void MainWindow::youthSelectionChanged()
{
    QList<QTreeWidgetItem *> selections = YouthTreeWidget->selectedItems();
    QTreeWidgetItem *selection = selections.first();

    if (m_current)
        disconnect(m_current, SIGNAL(modified()), this, SLOT(nameChanged()));

    if (selection->parent() != NULL)
    {
        m_current = m_youth->findYouth(selection->text(0));
        if (m_current)
        {
            connect(m_current, SIGNAL(modified()), this, SLOT(nameChanged()));
            if (m_current->quorum() == QuorumType::Deacon)
            {
                deaconwidget->load(m_current);
                m_layout->setCurrentWidget(deaconwidget);
            }
            else if (m_current->quorum() == QuorumType::Teacher)
            {
                m_layout->setCurrentWidget(empty);
            }
            else if (m_current->quorum() == QuorumType::Priest)
            {
                m_layout->setCurrentWidget(empty);
            }
            else
            {
                m_layout->setCurrentWidget(empty);
            }
        }
    }
}

void MainWindow::redisplayYouth()
{
	m_current = NULL;
	m_layout->setCurrentWidget(empty);
	
    generateDeacons();
    generateTeachers();
    generatePriests();
    generateRetired();
}

void MainWindow::generateDeacons()
{
    QList<QTreeWidgetItem*> list = 
    	YouthTreeWidget->findItems(QuorumType::NameOf(QuorumType::Deacon), Qt::MatchExactly);
    if (list.size() > 0)
    {
	    QTreeWidgetItem *topwidget = list.at(0);
	    topwidget->takeChildren();
	    
	    QList<YouthPtr> deacons = m_youth->quorum(QuorumType::Deacon);
	    QListIterator<YouthPtr> i(deacons);
	    while (i.hasNext())
	    {
	        YouthPtr thisYouth = i.next();
	        QTreeWidgetItem *thiswidget = new QTreeWidgetItem(QStringList(thisYouth->name()));
	        topwidget->addChild(thiswidget);
	    }
	    YouthTreeWidget->expandItem(topwidget);
    }
}

void MainWindow::generateTeachers()
{
    QList<QTreeWidgetItem*> list = YouthTreeWidget->findItems(QuorumType::NameOf(QuorumType::Teacher), Qt::MatchExactly);
    if (list.size() > 0)
    {
	    QTreeWidgetItem *topwidget = list.at(0);
	    topwidget->takeChildren();
	    
	    QList<YouthPtr> teachers = m_youth->quorum(QuorumType::Teacher);
	    QListIterator<YouthPtr> i(teachers);
	    while (i.hasNext())
	    {
	        YouthPtr thisYouth = i.next();
	        QTreeWidgetItem *thiswidget = new QTreeWidgetItem(QStringList(thisYouth->name()));
	        topwidget->addChild(thiswidget);
	    }
	    YouthTreeWidget->expandItem(topwidget);
    }
}

void MainWindow::generatePriests()
{
    QList<QTreeWidgetItem*> list = YouthTreeWidget->findItems(QuorumType::NameOf(QuorumType::Priest), Qt::MatchExactly);
    if (list.size() > 0)
    {
	    QTreeWidgetItem *topwidget = list.at(0);
	    topwidget->takeChildren();
	    
	    QList<YouthPtr> priests = m_youth->quorum(QuorumType::Priest);
	    QListIterator<YouthPtr> i(priests);
	    while (i.hasNext())
	    {
	        YouthPtr thisYouth = i.next();
	        QTreeWidgetItem *thiswidget = new QTreeWidgetItem(QStringList(thisYouth->name()));
	        topwidget->addChild(thiswidget);
	    }
	    YouthTreeWidget->expandItem(topwidget);
    }
}

void MainWindow::generateRetired()
{
    QList<QTreeWidgetItem*> list = YouthTreeWidget->findItems(QuorumType::NameOf(QuorumType::Retired), Qt::MatchExactly);
    if (list.size() > 0)
    {
	    QTreeWidgetItem *topwidget = list.at(0);
	    topwidget->takeChildren();
	    
	    QList<YouthPtr> retired = m_youth->quorum(QuorumType::Retired);
	    QListIterator<YouthPtr> i(retired);
	    while (i.hasNext())
	    {
	        YouthPtr thisYouth = i.next();
	        QTreeWidgetItem *thiswidget = new QTreeWidgetItem(QStringList(thisYouth->name()));
	        topwidget->addChild(thiswidget);
	    }
	    YouthTreeWidget->expandItem(topwidget);
    }
}

void MainWindow::nameChanged()
{
    if (m_current)
    {
        QList<QTreeWidgetItem *> selections = YouthTreeWidget->selectedItems();
        QTreeWidgetItem *selection = selections.first();

        if (selection->parent() != NULL)
        {
            selection->setText(0, m_current->name());
        }
    }
}

void MainWindow::print()
{
    if (m_current != NULL)
    {
        QString fileName = QFileDialog::getSaveFileName(this, tr("Save File"),
                QString(), tr("Adobe PDF (*.pdf)"));

        if (!fileName.isEmpty())
        {
            if (!fileName.endsWith(".pdf"))
                fileName.append(".pdf");

            QPrinter printer(QPrinter::HighResolution);
            printer.setOutputFileName(fileName);
            printer.setOrientation(QPrinter::Landscape);
            printer.setResolution(300);

            DeaconsWidget widget;
            widget.load(m_current);

            QPalette palette = widget.palette();
            palette.setColor(QPalette::Window, Qt::white);
            widget.setPalette(palette);

            QPixmap pixmap = QPixmap::grabWidget(&widget, widget.rect()).scaled(printer.pageRect().size(), Qt::IgnoreAspectRatio, Qt::SmoothTransformation);

            QPainter p;
            p.begin(&printer);
            p.drawPixmap(0, 0, pixmap);
            p.end();
        }
    }
    else
    {
        std::cout << "MainWindow::print() "
                  << "no youth has been selected." << std::endl;
    }
}

void MainWindow::open()
{
	QString filename = QFileDialog::getOpenFileName(this, tr("Open File"), QString(), tr("D2G (*.d2g)"));
	if (!filename.isEmpty() && !filename.isNull())
	{
		// clear out all the existing youth
		YouthManager::getInstanceOf()->clear();
		
		// load the new ones from the file
		YouthManager::getInstanceOf()->LoadFromFile(filename);
		
		m_activeFile = filename;
	}
}
void MainWindow::saveas()
{
    m_activeFile = QFileDialog::getSaveFileName(this, tr("Save File"), QString(), tr("D2G (*.d2g)"));
	if (!m_activeFile.isEmpty())
		YouthManager::getInstanceOf()->WriteToFile(m_activeFile);
}

void MainWindow::save()
{
	if (m_activeFile.isEmpty())
		QString m_activeFile = QFileDialog::getSaveFileName(this, tr("Save File"), QString(), tr("D2G (*.d2g)"));
	
	if (!m_activeFile.isEmpty())
		YouthManager::getInstanceOf()->WriteToFile(m_activeFile);
}

